package com.demo.controller;

import com.demo.entity.Customer;
import com.demo.repository.CustomerRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/customers")
public class CustomerController {

    @Autowired
    private CustomerRepo customerRepo;

    @PostMapping
    @ResponseStatus(code = HttpStatus.CREATED)
    public Customer save(@RequestBody Customer customer) {
        return customerRepo.save(customer);
    }

    //    @PageableDefault(size = 10, page = 0, sort = "customerId", direction = Sort.Direction.DESC)
    @GetMapping
    public Page<Customer> all(/*@PageableDefault*/ Pageable pageable) {
        return customerRepo.findAll(pageable);
    }

    @GetMapping("/{customerId}")
    public Customer findByCustomerId(@PathVariable Integer customerId) {
        return customerRepo.findById(customerId).orElseThrow(() -> new RuntimeException(
                "Customer [customerId=" + customerId + "] can't be found"
        ));
    }

    @DeleteMapping("/{customerId}")
    public ResponseEntity<?> deleteById(@PathVariable Integer customerId) {
        return customerRepo.findById(customerId).map(customer -> {
            customerRepo.delete(customer);
            return ResponseEntity.ok().build();
        }).orElseThrow(() -> new RuntimeException(
                "Customer [customerId=" + customerId + "] can't be found"
        ));
    }

    @PutMapping("/{customerId}")
    public ResponseEntity<Customer> updateById(@PathVariable Integer customerId, @RequestBody Customer newCustomer) {
        return customerRepo.findById(customerId).map(customer -> {
            customer.setCustomerName(newCustomer.getCustomerName());
            customer.setBirthday(newCustomer.getBirthday());
            customer.setPhoneNumber(newCustomer.getPhoneNumber());
            customerRepo.save(customer);
            return ResponseEntity.ok(customer);
        }).orElseThrow(() -> new RuntimeException(
                "Customer [customerId=" + customerId + "] can't be found"
        ));
    }
}
